"""
Case Type   : explain
Case Name   : gsql在加密模式下(-C)，错误执行explain(非语法错误)后执行的正确sql语句
Create At   : 2024/07/12
Owner       : songjing20
Description :
    1.建表
    2.执行explain错误语句，表中插入数据，查询表数据
    3.清理环境
Expect      :
    1.建表成功
    2.执行explain报错，执行insert 1次，表中1条数据
    3.清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class SQL(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.table = 't_explain_0092'
        self.Constant = Constant()

    def test_explain(self):
        self.logger.info(f'-----{os.path.basename(__file__)} start-----')
        step1 = '-----step1:建表;expect:建表成功-----'
        self.logger.info(step1)
        create_tb = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.table};"
            f"create table {self.table}(a int );", '-C')
        self.logger.info(create_tb)
        self.assertIn(self.Constant.CREATE_TABLE_SUCCESS, create_tb,
                      f"建表失败:{step1}")

        step2 = '-----step2:执行explain错误语句，表中插入数据，查询表数据;' \
                'expect:执行explain报错，执行insert 1次，表中1条数据-----'
        self.logger.info(step2)
        res = self.pri_sh.execut_db_sql(
            f'''explain select a();
            insert into {self.table} values(123);
            select * from {self.table};''', '-C')
        self.logger.info(res)
        self.assertEqual(res.count(self.Constant.INSERT_SUCCESS_MSG), 1,
                         f"执行失败:{step2}")
        self.assertEqual(res.splitlines()[-2].strip(), '123', f"执行失败:{step2}")
        self.assertIn('1 row', res, f"执行失败:{step2}")
        self.assertIn('ERROR', res.splitlines()[0], f"执行失败:{step2}")

    def tearDown(self):
        step3 = '-----step3:清理环境;expect:成功-----'
        self.logger.info(step3)
        drop_res = self.pri_sh.execut_db_sql(f"drop table {self.table};")
        self.logger.info(drop_res)
        self.assertIn(self.Constant.DROP_TABLE_SUCCESS, drop_res,
                      f"执行失败:{step3}")
        self.logger.info(f'-----{os.path.basename(__file__)} end-----')
